package com.silence.tool.tool;

import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.File;
import java.io.IOException;

import static lombok.AccessLevel.PRIVATE;

/**
 * @Author silence
 * @Email meng.wl@neusoft.com
 * @Date 2025-01-20 09:41
 * @Description pdf 分割工具类
 */
@Slf4j
@NoArgsConstructor(access = PRIVATE)
public class PdfSplitUtil {

    /**
     * 将PDF拆分为单页文件
     *
     * @param sourcePath 源PDF文件路径
     * @param targetDir  目标目录
     */
    public static void splitToPages(String sourcePath, String targetDir) throws IOException {
        try {
            // 1. 验证源文件
            FileUtils.validateFileReadable(sourcePath);

            // 2. 获取源文件名（不带扩展名）用于创建子目录
            String sourceFileName = new File(sourcePath).getName();
            String baseName = sourceFileName.substring(0, sourceFileName.lastIndexOf('.'));

            // 3. 创建输出目录（包含源文件名的子目录）
            String outputDir = new File(targetDir, baseName + "_split").getAbsolutePath();
            String normalizedOutputDir = FileUtils.ensureDirectoryExists(outputDir);

            log.info("开始分割PDF: {} -> {}", sourcePath, normalizedOutputDir);

            // 4. 加载并分割PDF
            PDDocument document = Loader.loadPDF(new File(sourcePath));
            try (document) {
                int totalPages = document.getNumberOfPages();
                log.info("PDF总页数: {}", totalPages);

                // 直接复制页面方式
                for (int i = 0; i < totalPages; i++) {
                    String pageFileName = String.format("page_%d.pdf", i + 1);
                    String outputPath = new File(normalizedOutputDir, pageFileName).getAbsolutePath();

                    // 为每一页创建新的文档
                    try (PDDocument pageDoc = new PDDocument()) {
                        pageDoc.addPage(document.getPage(i));
                        pageDoc.save(outputPath);
                        log.info("已保存第{}页: {}", i + 1, outputPath);
                    }
                }

                log.info("PDF分割完成，共处理{}页", totalPages);
            }
        } catch (Exception e) {
            log.error("PDF分割失败：", e);
            throw new IOException("PDF分割失败: " + e.getMessage(), e);
        }
    }

    /**
     * 按页码范围分割PDF
     *
     * @param sourcePath 源路径
     * @param targetPath 目标路径
     * @param startPage  起始页码
     * @param endPage    结束页码
     * @throws IOException IO异常
     */
    public static void splitByRange(String sourcePath, String targetPath,
                                    int startPage, int endPage) throws IOException {
        try {
            // 1. 验证源文件
            FileUtils.validateFileReadable(sourcePath);

            // 2. 确保目标文件的父目录存在
            String normalizedTargetPath = FileUtils.ensureParentDirectoryExists(targetPath);

            // 3. 验证页码范围
            if (startPage < 1 || endPage < startPage) {
                throw new IllegalArgumentException(
                        String.format("无效的页码范围: %d-%d", startPage, endPage));
            }

            // 4. 执行分割
            PDDocument sourceDocument = Loader.loadPDF(new File(sourcePath));
            try (sourceDocument) {
                int totalPages = sourceDocument.getNumberOfPages();
                if (startPage > totalPages) {
                    throw new IllegalArgumentException(
                            String.format("起始页码(%d)超出文档总页数(%d)", startPage, totalPages));
                }

                endPage = Math.min(endPage, totalPages);

                Splitter splitter = new Splitter();
                splitter.setStartPage(startPage);
                splitter.setEndPage(endPage);

                // 创建新文档
                PDDocument newDocument = new PDDocument();
                try (newDocument) {
                    // 复制指定范围的页面到新文档
                    for (int i = startPage; i <= endPage; i++) {
                        // 注意：PDFBox页码从0开始，所以要减1
                        newDocument.addPage(sourceDocument.getPage(i - 1));
                    }

                    // 保存新文档
                    newDocument.save(normalizedTargetPath);
                    log.info("已保存页码{}至{}到: {}",
                            startPage, endPage, normalizedTargetPath);
                }
            }
        } catch (Exception e) {
            log.error("PDF分割失败：", e);
            throw new IOException("PDF分割失败: " + e.getMessage(), e);
        }
    }

}